import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage } from "element-plus";
import nprogress from 'nprogress'
import BaseUrl from "@/utils/BaseUrl/BaseUrl";
import { getToken } from "@/utils/Cookies/Cookies";
import { BaseResponse } from '@/PageData/index'
import errorHandle from '@/api/status/status'

const instance = axios.create({
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
    "Access-Control-Allow-Origin-Type": '*'
  },
  timeout: 1000 * 30,
  baseURL: BaseUrl,
  withCredentials: false,
});


instance.interceptors.request.use((config: AxiosRequestConfig) => {
  nprogress.start();
  let token = getToken();
  if (token) {
    config.headers = {
      Authorization: 'Bearer ' + token
    }
  }
  return config;


}, error => {
  ElMessage.error(error.data.error.message);
  return Promise.reject(error.data.error.message);
})


instance.interceptors.response.use((res: AxiosResponse<BaseResponse>) => {
  nprogress.done();
  // 请求成功
  if (res.status === 200 || res.status === 204) {

    return Promise.resolve(res.data);

  } else {
    return Promise.reject(res);
  }
}, error => {
  const { response } = error;
  if (response) {
    errorHandle(response.status, response.data.message);
    return Promise.reject(response);
  }
});

export default instance